package com.tengju.bff.interfaces.covercharge.controller.admin;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Throwables;
import com.idanchuang.component.base.JsonResult;
import com.tengju.bff.interfaces.covercharge.entity.vo.*;
import com.tengju.bff.interfaces.covercharge.service.ITaskService;
import com.tengju.bff.interfaces.covercharge.util.DateTimeUtils;
import com.tengju.bff.interfaces.covercharge.util.ExcelExportUtil;
import com.tengju.bff.interfaces.covercharge.util.OssUtil;
import com.tengju.bff.interfaces.shared.ApiResponse;
import com.tengju.bff.interfaces.shared.servlet.ManageEntrance;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

@Controller
@Slf4j
@RequestMapping("/manage/task")
@Api(value = "task", tags = "任务管理")
@ManageEntrance
public class TaskController {

    @Autowired
    private ITaskService taskService;


    @GetMapping("/list")
    @ResponseBody
    @ApiOperation(value = "查询任务信息列表")
    @RequiresRoles("sso")
    public ApiResponse<Page<TaskResultVo>> list(TaskQuery taskQuery) {
        Integer pageNo = taskQuery.getPageNo();
        Integer limit = taskQuery.getLimit();
        return ApiResponse.newSuccess(taskService.queryTaskList(new Page<>(pageNo, limit), taskQuery));
    }


    @RequestMapping("/errorMsg/export")
    @ApiOperation(value = "下载错误提示内容")
    public void export(HttpServletRequest request, HttpServletResponse response, OssFileDownloadReq downloadReq) {
        String result;
        try {
            byte[] downloadResult = OssUtil.getFileByteByKey(downloadReq.getFileKey());
            result = new String(downloadResult, StandardCharsets.UTF_8);
        } catch (Exception e) {
            result = downloadReq.getFileKey() + "文件下载错误!异常信息：" + Throwables.getStackTraceAsString(e);
        }
        taskService.downloadFile(result.getBytes(), request, response, downloadReq.getFileKey());
    }


}
